package com.example.testapplication;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.testapplication.event.MessageEvent;
import com.example.testapplication.event.StickyEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

// eventbus的发送数据页面
public class EventBusSendActivity extends AppCompatActivity {
    private TextView tv_title;
    private Button bt_eventbus_send_main;
    private Button bt_eventbus_send_sticky;
    private TextView tv_eventbus_send_result;
    boolean isFirstFlag = true;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_busend);
        tv_title = (TextView)findViewById(R.id.tv_title);
        bt_eventbus_send_main = (Button)findViewById(R.id.bt_eventbus_send_main);
        bt_eventbus_send_sticky = (Button)findViewById(R.id.bt_eventbus_send_sticky);
        tv_eventbus_send_result = (TextView)findViewById(R.id.tv_eventbus_send_result);
        tv_title.setText("EventBus发送数据页面");


        initListener(); // 监听事件

    }

    private void initListener() {
        // 主线程发送数据按钮点击事件处理
        bt_eventbus_send_main.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 4.发送消息
                EventBus.getDefault().post(new MessageEvent("主线程发送过来的数据"));
                // 结束当前页面
                finish();


            }
        });

        // 接收粘性事件数据的点击事件处理
        bt_eventbus_send_sticky.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 粘性事件4
                if(isFirstFlag){
                    isFirstFlag = false;

                    // 粘性事件4.注册
                    EventBus.getDefault().register(EventBusSendActivity.this);

                }

            }
        });

    }
    // 粘性事件3 接收粘性事件
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void StickyEventBus(StickyEvent event){
        // 显示接收数据
        tv_eventbus_send_result.setText(event.msg);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 粘性事件5 解注册
        EventBus.getDefault().removeAllStickyEvents();
        EventBus.getDefault().unregister(EventBusSendActivity.this);

    }
}
